package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class ServeServiceImpl  extends ServiceImpl<ServeMapper, Serve> implements IServeService  {

    @Autowired
    private ServeItemMapper serveItemMapper ;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;

    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 查询区域服务信息并进行缓存
     *
     * @param id 对应serve表的主键
     * @return 区域服务信息
     */
    @Override
    @Cacheable(value = RedisConstants.CacheName.SERVE,key = "#id" , cacheManager =RedisConstants.CacheManager.ONE_DAY)
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }

    /**
     * 分页查询
     *
     * @param dto 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO dto) {
        return PageHelperUtils.selectPage(dto,
                () -> baseMapper.queryList(dto.getRegionId()));
    }
    /**
     * 服务项新增
     *
     * @param serveUpsertReqDTOList 新增服务项
     */
    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //1.校验服务项是否为启用状态，不是启用状态不能新增
        for (ServeUpsertReqDTO  serveUpsertReqDTO : serveUpsertReqDTOList ){
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            //如果服务项信息不存在或未启用
            if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus() ){
                throw  new ForbiddenOperationException("该服务项信息不存或者该服务项信息未启用");
            }
            //2.校验是否重复新增
           Integer count = lambdaQuery()
                    .eq(Serve :: getRegionId,serveUpsertReqDTO.getRegionId())
                    .eq(Serve :: getServeItemId,serveUpsertReqDTO.getServeItemId())
                    .count();
            if (count > 0){
                throw new ForbiddenOperationException("服务项名称不可重复");
            }
            //3.新增服务
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }


    /**
     * 修改服务价格
     *
     * @param id ID ,price 价格
     */
    @Override
    @Transactional
    public  Serve update(Long id, BigDecimal price) {
        boolean update = lambdaUpdate().eq(Serve::getId, id).set(Serve::getPrice, price)
                .update();
        if (!update){
                throw  new CommonException("服务价格修改失败");
        }



    return baseMapper.selectById(id);

    }

    /**
     * 服务上架
     *
     * @param id ID
     */
    @Override
    @Transactional
    @CachePut(value = RedisConstants.CacheName.SERVE,key = "#id")
    public Serve onSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //在草稿状态和下架状态，才可以上架
        if (!(saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())){
            throw new ForbiddenOperationException("在草稿状态和下架状态才可以上架");

        }
        //服务向id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("该服务不存在");
        }

        Integer activeStatus = serveItem.getActiveStatus();
        if (!( FoundationStatusEnum.ENABLE.getStatus() ==activeStatus)){
            throw new ForbiddenOperationException("服务为启动才能上架");
        }

        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if ( !update){
            throw new ForbiddenOperationException("服务启动失败");
        }

        addServeSync(id);
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("服务项不存在");
        }
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("已上架服务不可删除，请先下架");
        }
        // 3. 执行删除操作
        int result = baseMapper.deleteById(id);

    }

    @Override
    @Transactional
    @CacheEvict(value = RedisConstants.CacheName.SERVE,key = "#id")
    public Serve offSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //下架状态
        Integer saleStatus = serve.getSaleStatus();
        //在草稿状态和下架状态，才可以上架
        if (!(saleStatus == FoundationStatusEnum.ENABLE.getStatus() )){
            throw new ForbiddenOperationException("在上架状态才可以下架");
        }

        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if ( !update){
            throw new ForbiddenOperationException("服务下架失败");
        }

        serveSyncMapper.deleteById(id);
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional
    public Serve onHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        Integer isHot = serve.getIsHot();
        if (isHot == 1){
            throw new ForbiddenOperationException("状态为热门，不可以再设置为热门");
        }
        lambdaUpdate().eq(Serve :: getId ,id).set(Serve ::getIsHot,1).update();
        return baseMapper.selectById(id);
    }

    @Override
    public Serve offHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        Integer isHot = serve.getIsHot();
        if (isHot == 0){
            throw new ForbiddenOperationException("状态为非热门，不可以再设置为非热门");
        }
        lambdaUpdate().eq(Serve :: getId ,id).set(Serve ::getIsHot,0).update();
        return baseMapper.selectById(id);
    }

    @Override
    public int queryStatus(Long regionId, Integer saleStatus) {
        LambdaQueryWrapper<Serve> eq = Wrappers.<Serve>lambdaQuery().eq(Serve::getRegionId, regionId).eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(eq);
    }

    /**
     * 根据服务项id和售卖状态查询关联服务数量
     * @param  serveItemId  服务项id
     * @param saleStatus 售卖状态，0：草稿，1下架，2上架。可传null，即查询所有状态
     * @return 服务数量
     */
    @Override
    public int queryServeCountByServeItemIdAndSaleStatus(Long serveItemId, int saleStatus) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getServeItemId, serveItemId)
                .eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(queryWrapper);
    }
}
